<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 12px">
      <!-- 查询区域 -->
      <a-form-model :label-col="{ span: 7 }" :wrapper-col="{ span: 16 }" layout="inline" @keyup.enter.native="onQuery">
        <a-form-model-item label="报表名称">
          <a-input v-model="form.name" placeholder="请输入" />
        </a-form-model-item>
        <a-form-model-item :wrapper-col="{ offset: 0 }" style="margin-bottom: 0">
          <a-button type="primary" @click="onQuery"> 查询 </a-button>
          <a-button style="margin-left: 10px" @click="onResetForm"> 重置 </a-button>
        </a-form-model-item>
      </a-form-model>
    </a-card>
    <a-card :bordered="false">
      <!-- 操作按钮区域 -->
      <div class="table-operator">
          <a-button type="primary" @click="handleManage('add')" v-has="'operator_report:add'">新增报表</a-button>
      </div>
      <!-- 表格展示 -->
      <div class="table-page-content">
        <custom-table
          ref="table"
          rowKey="id"
          :showAlert="false"
          :showSelection="false"
          :loading="loading"
          :columns="columns"
          :dataSource="pageData"
          @change="onTableChange"
        >
          <template slot="type" slot-scope="text">
            {{filterMultiDictText(text)}}
          </template>
          <!--操作-->
          <template slot="action" slot-scope="text, record">
            <a-button @click="handleBtn('preview',record)" type="link" v-has="'item_report:preview'">查看</a-button>
            <a-button @click="handleBtn('edit',record)" type="link" v-has="'item_report:edit'">编辑</a-button>
            <!-- <a-button @click="handleManage('collection',record)" type="link">收藏模板</a-button> -->
            <a-button @click="handleManage('delete',record)" type="link" v-has="'item_report:delete'">删除模板</a-button>
            <a-button @click="handleManage('copy',record)" type="link" v-has="'item_report:copy'">复制模板</a-button>
            <a-button @click="handleManage('share',record)" type="link" v-has="'item_report:share'">分享模板</a-button>
          </template>
        </custom-table>
      </div>
    </a-card>
    <a-modal v-model="visible" :title="!shared?'创建分享链接':'分享链接'" on-ok="sharedOk">
      <a-form-model layout="inline">
        <a-form-model-item label="过期时间" v-if="!shared">
          <a-radio-group :options="plainOptions" v-model="formItem.termOfValidity" />
        </a-form-model-item>
        <a-form-model-item label="预览链接" v-if="shared">
          <a-input v-model="formItem.previewUrl" placeholder="链接" style="width:380px;" />
        </a-form-model-item>
        <a-form-model-item label="预览密码" v-if="shared">
          <a-input v-model="formItem.previewLock" placeholder="密码" />
        </a-form-model-item>
      </a-form-model>
      <template slot="footer" v-if="!shared">
        <a-button key="back" @click="handleCancel"> 取消 </a-button>
        <a-button key="submit" type="primary" @click="handleShare('0')"> 创建连接 </a-button>
      </template>
      <template slot="footer" v-else>
        <a-button key="submit" type="primary" @click="handleShare('1')"> 取消分享 </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from "@/store/mutation-types"
import * as reportApi from '@/api/modules/report.js'
import CustomTable from '@/components/zxd/Table/CustomTable'

export default {
  components: {
    CustomTable,
  },
  data() {
    return {
      loading: false,
      visible: false,
      shared: false,
      reportId: null,
      plainOptions: [
        { label: '永久有效', value: '1' },
        { label: '7天', value: '2' },
        { label: '1天', value: '3' },
      ],
      formItem: {
        termOfValidity: '1'
      },
      form: {
        // type: 'datainfo'
      },
      columns: [
        {
          title: "序号",
          dataIndex: "order",
          width: 50,
          align: "center",
          customRender: (text, record, index) =>
            `${(this.pageFilter.pageNo - 1) * this.pageFilter.pageSize +
              (index + 1)}` //序号分页后连续
        },
        {
          title: '报表名称',
          dataIndex: 'name',
          width: 150,
          align: 'center',
        },
        {
          title: '报表类型',
          dataIndex: 'type',
          width: 50,
          align: 'center',
          scopedSlots: { customRender: 'type' },
        },
        {
          title: '操作',
          width: 120,
          align: 'center',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
        },
      ],
      pageFilter: {
        pageNo: 1,
        pageSize: 10,
      },
      pageData: {},
      datas: [
        {text: '打印设计', value: 'printinfo'},
        {text: '数据报表', value: 'datainfo'},
        {text: '图形报表', value: 'chartinfo'}
      ]
    }
  },
  async mounted() {
    this.onQuery()
  },
  methods: {
    onQuery() {
      this.pageFilter.pageNo = 1
      this.refreshTable()
    },
    onResetForm() {
      this.form = {}
      this.pageFilter.pageNo = 1
      this.pageFilter.pageSize = 10
      this.refreshTable()
    },
    onTableChange(pagination, pageFilter, sorter) {
      let keyMap = { currentPage: 'pageNo' }
      let paginations = Object.keys(pagination).reduce((newData, key) => {
        let newKey = keyMap[key] || key
        newData[newKey] = pagination[key]
        return newData
      }, {})
      this.pageFilter = Object.assign({}, this.pageFilter, paginations)
      this.refreshTable()
    },
    refreshTable() {
      let form = Object.assign({}, this.form, this.pageFilter)
      this.loading = true
      reportApi
        .getList(form)
        .then((res) => {
          if (res.success) {
            this.pageData = res.result
            this.loading = false
            this.$refs.table.onClearRowKeys()
          } else {
            this.loading = false
          }
        })
        .catch((e) => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    handleManage(type, record) {
      let that = this
      if (type==='add') {
        reportApi.reportSave({}).then((res) => {
          if (res.success) {
            let record = res.result
            this.handleBtn('add', record)
          }
        })
        .catch((e) => {
          this.$message.warn('请求失败！')
        })
      } else if(type==='delete') {
        this.$confirm({
          title: '确定删除？',
          onOk() {
            reportApi.reportdelete({id: record.id}).then((res) => {
              if (res.success) {
                that.onQuery()
              }
            })
            .catch((e) => {
              that.$message.warn('请求失败！')
            })
          }
        })
      } else if(type==='copy') {
        this.$confirm({
          title: '确定复制？',
          onOk() {
            reportApi.reportCopy({id: record.id}).then((res) => {
              if (res.success) {
                that.onQuery()
              }
            })
            .catch((e) => {
              that.$message.warn('请求失败！')
            })
          }
        })
      } else if(type==='collection') {
        this.$confirm({
          title: '是否确认设置为模板?', //是否确认取消模板?
          onOk() {
            // template为1收藏，为0取消收藏
            reportApi.setTemplate({id: record.id, template: record.template}).then((res) => {
              if (res.success) {
                that.onQuery()
              }
            })
            .catch((e) => {
              that.$message.warn('请求失败！')
            })
          }
        })
      } else if(type==='share') {
        this.reportId = record.id
        reportApi.queryJurisdiction({reportId: this.reportId}).then((res) => {
          if (res.success) {
            this.visible = true;
            let domianURL = window._CONFIG['domianURL']
            if(res.result) {
              this.formItem = res.result
              // 未分享
              if(this.formItem && this.formItem.status ==='1') {
                this.shared = false;
              // 已分享
              } else {
                this.shared = true;
              }
              if(this.formItem && this.formItem.previewUrl) this.$set(this.formItem, 'previewUrl', domianURL + this.formItem.previewUrl)
            } else {
              this.shared = false;
            }
          }
        })
        .catch((e) => {
          this.$message.warn('请求失败！')
        })
      }
    },
    // 操作
    handleBtn(type, record) {
      let token = Vue.ls.get(ACCESS_TOKEN)
      let domianURL = window._CONFIG['domianURL']
      let url
      switch(type){
        case 'add': //新增模板
          url = `${domianURL}/jmreport/index/${record.id}?token=${token}&menuType=datainfo`
          break;
        case 'preview': //预览模板
          url = `${domianURL}/jmreport/view/${record.id}?token=${token}`
          break;
        case 'edit': //编辑模板
          url = `${domianURL}/jmreport/index/${record.id}?token=${token}`
          break;
      }
      window.open(url)
    },
    filterMultiDictText(text) {
      return this.$filterDictText(this.datas, text)
    },
    // 创建分享、取消分享
    handleShare(status) {
      let obj = {}
      if (status==0) {
        obj = {
          reportId: this.reportId, 
          status: status, // 0为创建分享,1为取消分享
          termOfValidity: this.formItem.termOfValidity
        }
      } else {
        obj = {
          id: this.formItem.id,
          reportId: this.reportId,
          status: status // 0为创建分享,1为取消分享
        }
      }
      reportApi.addAndEdit(obj).then((res) => {
          if (res.success) {
            let domianURL = window._CONFIG['domianURL']
            if(res.result && status==0) {
              this.shared = true;
              this.formItem = res.result
              this.$set(this.formItem, 'previewUrl', domianURL + res.result.previewUrl)
            } else if(res.result && status==1) {
              this.$message.success('取消分享成功！')
              this.shared = false;
              this.visible = false;
              this.formItem = {}
              this.$set(this.formItem, 'termOfValidity', '1')
            } else {
              this.$message.warn(res.message)
            }
          }
        })
        .catch((e) => {
          this.$message.warn('请求失败！')
        })
    },
    // 关闭
    handleCancel(e) {
      this.visible = false;
    }
  }
}
</script>
<style lang="less" scoped>
/deep/.ant-btn.ant-btn-link {
  padding: 0 5px;
}
</style>
